package com.yk.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yk.api.system.dto.VideoDTO;
import com.yk.common.core.constant.CacheConstants;
import com.yk.common.core.constant.NumberConstant;
import com.yk.common.core.utils.HttpUtils;
import com.yk.common.redis.service.RedisService;
import com.yk.system.entity.Video;
import com.yk.system.mapper.VideoMapper;
import com.yk.system.service.VideoService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 摄像头 服务类
 *
 * @author lmx
 * @since 2023-11-07
 */
@Service
@RequiredArgsConstructor
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements VideoService {

    private final RedisService redisService;

    @Override
    public List<VideoDTO> listByGroupId(Long id) {
        return baseMapper.listByGroupId(id);
    }

    @Override
    public List<VideoDTO> listByParam(VideoDTO param) {
        return baseMapper.listByParam(param);
    }

    @Override
    public void getToken(List<VideoDTO> videoDTOS) {
        if (CollUtil.isEmpty(videoDTOS)) {
            return;
        }

        StringBuffer buffer = new StringBuffer();
        videoDTOS.forEach(it -> {
            buffer.append("appKey=").append(it.getAppkey()).append("&appSecret=").append(it.getSecret());
            String token = getParam(it.getId(), buffer.toString());
            it.setToken(token);
            buffer.setLength(0);
        });
    }

    @Override
    public void getToken(VideoDTO dto) {
        String buffer = "appKey=" + dto.getAppkey() + "&appSecret=" + dto.getSecret();
        String token = getParam(dto.getId(), buffer);
        dto.setToken(token);
    }

    /**
     * 获取缓存的token或申请新token
     */
    private String getParam(Long videoId, String param) {
        String token = redisService.get(CacheConstants.EZVIZ_TOKEN_KEY + videoId);
        String url = "https://open.ys7.com/api/lapp/token/get";
        if (StrUtil.isEmpty(token)) {
            JSONObject result = HttpUtils.postFormUrlEncoded(url, param);
            if (Objects.isNull(result)) {
                return null;
            }
            if (NumberConstant.TWO_HUNDRED_STR.equals(result.getStr("code"))) {
                token = result.getJSONObject("data").getStr("accessToken");
            }
            if (StrUtil.isNotEmpty(token)) {
                redisService.setCacheObject(CacheConstants.EZVIZ_TOKEN_KEY + videoId, token, 6L, TimeUnit.DAYS);
            }
        }
        return token;
    }
}